<template>

    <div>
        <Tablefilter :filter="filterModel"
                     @search="search"
                     @editStatus="editStatus"
                     :actions="actions"
                     @action="action"
                     :delShow="false"
                     :editStatusShow="false"
                     :addShow="false"></Tablefilter>

        <commonTable :getTableList="getTableList()"
                     :refresh.sync="refresh"
                     :filter="filter"
                     :stripe="false"
                     :editStatusShow="false"
                     :selectRow.sync="selectRow"
                     :changeRow.sync="changeRow"
                     :rowClassName="rowClassName"
                     :columns="columns">
            <div slot="tableInfo" class="tableInfo">
                <div><span>{{$t('common.allOrder')}}：</span><span>{{ownerOrder.totalCount}}</span></div>
                <div><span>{{$t('common.monthOrder')}}：</span><span>{{ownerOrder.monthCount}}</span></div>
                <div><span>{{$t('common.dayOrder')}}：</span><span>{{ownerOrder.todayCount}}</span></div>
                <div><span>{{$t('common.monthTurnover')}}：</span><span>{{ownerOrder.monthTurnover}}</span></div>
                <div><span>{{$t('common.dayTurnover')}}：</span><span>{{ownerOrder.todayTurnover}}</span></div>
            </div>
        </commonTable>
        <orderEdit ref="orderEdit" :data="editData" :changeRow.sync="changeRow"></orderEdit>
    </div>
</template>

<script>

  import Tablefilter from '../components/table/commonTableFilter'
  import commonTable from '../components/table/commonTable'
  import {mapState} from 'vuex'
  import orderEdit from './orderEdit'
  import {orderState} from '../../config/index'

  export default {
    name: "orderList",
    components: {
      Tablefilter,
      orderEdit,
      commonTable
    },
    data() {
      let validatemealDetils = (rule, value, callback) => {
        if (value.length === 1 && value[0].count === 0) {
          callback(new Error(this.$t('packages.mealDetilsTip')));
        } else {
          callback();
        }
      };
      return {
        selectRow: [],
        editData: {},
        filter: {},
        changeRow: {},
        refresh: false,
        columns: [
          {
            label: this.$t('common.operate'),
            prop: 'operate',
            render: this.render('operate'),
            width: 90,
            tooltip: false,
            fixed: 'right'
          },
          {type: 'selection', width: 55},
          {label: this.$t('common.productName'), prop: 'productName'},
          {label: this.$t('common.orderId'), prop: 'orderId', width: 70},
          {label: this.$t('common.orderState'), prop: 'orderState', render: this.render('orderState')},
          {label: this.$t('common.orderDetail'), prop: 'orderDetail', render: this.render('orderDetail')},
          // {label: this.$t('common.userName'), prop: 'userName'},
          {label: this.$t('common.phoneNumber'), prop: 'phoneNumber'},
          {label: this.$t('common.email'), prop: 'email'},
          {label: this.$t('common.absentee'), prop: 'absentee', render: this.render('absentee')},
          {label: 'ip', prop: 'ip'},
          // {label:  this.$t('common.userNotes'), prop: 'userNotes'},
          {label: this.$t('common.orderTime'), prop: 'orderTime'},
          // {label:  this.$t('common.contactTime'), prop: 'contactTime', width: 90},
          {label: this.$t('common.productNumber'), prop: 'productNumber'},
          {label: this.$t('common.price'), prop: 'price'},
          {label: this.$t('common.optimizer'), prop: 'optimizer'},
          {label: this.$t('common.checkUser'), prop: 'checkUser'},
          {label: this.$t('common.isVerify'), prop: 'isVerify', render: this.render('isVerify')},
        ],
        filterModel: {
          adId: {
            label: this.$t('common.adId'),
            value: '',
          },
          productId: {
            label: this.$t('common.productId'),
            value: '',
          },
          productName: {
            label: this.$t('common.productName'),
            value: '',
          },
          creator: {
            label: this.$t('common.optimizer'),
            value: '',
          },
          phone: {
            label: this.$t('common.phoneNumber'),
            value: ''
          },
          checkUser: {
            label: this.$t('common.checkUser'),
            value: ''
          },
          country: {
            label: this.$t('common.country'),
            value: '',
            options: []
          },
          orderState: {
            label: this.$t('common.orderState'),
            value: '',
            options: orderState
          },
          logisticsType: {
            label: this.$t('common.logistics'),
            value: '',
            options: [{
              label: this.$t('common.TianLongLogistics'),
              value: 1,
            }, {
              label: this.$t('common.JNELogistics'),
              value: 2,
            }, {
              label: this.$t('common.JXLogistics'),
              value: 3,
            },]
          },
          absentee: {
            label: this.$t('common.absentee'),
            value: '',
            options: [{
              label: this.$t('common.valid'),
              value: 0,
            }, {
              label: this.$t('common.invalid'),
              value: 1,
            },]
          },
          time: {
            label: this.$t('common.time'),
            value: '',
            time: true,
          },
        },
        actions: [/*{
                    label:this.$t('common.createExpressId'),
                    type:'dropDown',
                    dropItem:[{
                        label:this.$t('common.TianLongLogistics'),
                        value:0,
                    },{
                        label:this.$t('common.JNELogistics'),
                        value:1,
                    },{
                        label:this.$t('common.JXLogistics'),
                        value:2,
                    },],
                    value:'setExpressId'
                },*/{
          label: this.$t('common.exportOrder'),
          type: 'dropDown',
          dropItem: [{
            label: this.$t('common.TianLongLogistics'),
            value: 0,
          }, {
            label: this.$t('common.JNELogistics'),
            value: 1,
          }, {
            label: this.$t('common.JXLogistics'),
            value: 2,
          },],
          value: 'exportOrder'
        }],
        ownerOrder: {}
      }
    },
    methods: {
      search(filter) {
        this.filter = filter
        this.refresh = true
      },
      // 修改审核状态
      editStatus() {
        console.log(this.selectRow);
        console.log(this.filterModel);
        this.refresh = true;
      },
      delTable(Id) {

      },
      action(key, filter) {

        if (key.value === 'exportOrder') {
          this.exportOrder(key, filter);
          return true
        }
        if (key.value === 'setExpressId') {
          if (!this.actionCheck()) return
          let params = {
            orderId: this.selectRow.map(v => {
              return v.orderId
            }),
            logisticsType: key.type
          }
          this.setExpressId(params);
          return true
        }

      },
      actionCheck() {
        if (this.selectRow.length == 0) {
          this.$message.warning(this.$t('common.selectActionTip'))
          return false
        } else {
          return true
        }
      },
      getTableList() {
        console.log(this.$orderList);
        return this.$orderList
      },
      rowClassName({row, rowIndex}) {
        if (row.orderState === 2) {
          return 'error-row';
        } else if (row.orderState === 8) {
          return 'info-row';
        } else if (row.orderState === 1) {
          return 'success-row';
        } else if (rowIndex % 2 === 1) {
          return 'striped-row'
        }
        return '';
      },
      render(prop) {
        let render = {}
        if (!prop) return;
        render.isVerify = (h, params) => {
          let render = ''
          if (params.row.isVerify) {
            render = this.$t('common.isVerified')
          } else {
            render = this.$t('common.unVerified')
          }
          return h('div', render)
        }
        render.absentee = (h, params) => {
          // let render = ''
          let render = params.row.absentee
          // if (params.row.absentee) {
          //     render = this.$t('common.invalid')
          // } else if(params.row.absentee === 0) {
          //     render = this.$t('common.valid')
          // }
          return h('div', render)
        }
        render.operate = (h, params) => {
          return h('div', [
            h("el-button",
              {
                props: {
                  type: 'warning',
                  size: 'mini'
                },
                style: {
                  marginLeft: '5px'
                },
                on: {
                  click: () => {
                    this.editData = params.row
                    this.$refs.orderEdit.changeVisiable()
                  }
                }
              },
              this.$t('common.edit')
            )
          ])
        }
        render.orderDetail = (h, params) => {
          let renders = []
          let details = this.orderDetail(params.row.orderDetail)
          for (let [k, v] of Object.entries(details)) {
            let render = h('span',
              v.join(' ') + '  '
            )
            renders.push(render)
          }
          return h('div', renders)
        }
        render.orderState = (h, params) => {
          let render = this.$t('option.' + orderState[params.row.orderState].label)
          return h('div', render)
        }
        return render[prop]
      },
      storeAll() {
        let params = {
          pageSize: 99999,
          currentPage: 1,
        }
        this.$storeAll(params).then(response => {
          if (response.data) {
            let warehouseOptions = []
            response.data.forEach((v) => {
              let option = {
                value: v.id,
                label: v.wareHouseName,
              }
              warehouseOptions.push(option)
            })
            this.$store.commit('saveWarehouse', warehouseOptions)
          }
        })
      },
      setExpressId(params) {
        this.$setExpressId(params).then(response => {
          if (response && response.code === 'success') {
            this.$message.success(this.$t('common.success'))
            this.refresh = true
          } else {
            this.$message.error(this.$t('common.error'))
          }
        })
      },
      exportOrder(key, filter) {
        let params = Object.assign(filter, {expressType: key.type})

        this.$exportOrder(params).then(response => {
          if (response && response.code === 'success') {
            let url = response.data;
            window.location.href = url;

          } else {
            this.$message.error(this.$t('common.error'))
          }
        })
      },
      getOrdersInfo() {
        this.$getOrdersInfo({}).then(reponse => {
          if (reponse && reponse.code === 'success') {
            this.ownerOrder = reponse.data
          } else {
            this.ownerOrder = {}
          }
        })
      },
      orderDetail(str) {
        let attr = {}
        if (!str) return {}
        for (let [key, item] of Object.entries(JSON.parse(str))) {
          if (key === 'package') continue
          let unique = /(.*?[)(\d*)(])/.test(key) ? key.replace(/(.*?[\[])(\d*)([\]])/, '$2') : 0
          if (attr[unique]) {
            attr[unique].push(item)
          } else {
            attr[unique] = [item]
          }
        }
        return attr
      },
    },
    mounted() {
      console.log(this.columns, this.userInfo);
      const {userType} = this.userInfo;
      if(userType === 2) {
        this.columns = this.columns.filter((item)=> item.prop !== 'phoneNumber')
      }
      this.filterModel.country.options = this.countryOptions
      // this.filterModel.type.options = this.productTypeOptions
    },
    created() {
      this.getOrdersInfo()
      this.storeAll()
    },
    computed: {
      ...mapState(['countryOptions', 'productTypeOptions', 'userInfo'])
    },
  }
</script>

<style lang="less">
    .tableInfo {
        div {
            padding-right: 20px;
            display: inline-block;
        }
    }

    .error-row {
        background-color: #f56c6c !important;
    }

    .info-row {
        background-color: #409eff !important;
    }

    .success-row {
        background-color: #67c23a !important;
    }

    .striped-row {
        background-color: #FAFAFA !important;
    }

    body .el-table__fixed-right {
        top: 0.5px
    }
</style>